<template>
  <collapse-card title="填写基本信息">
    <div class="wrap">
      <el-form
        ref="refForm"
        style="width: 100%"
        label-width="110px"
        :model="form"
        :rules="chooseYjxs ? yjxsRules : rules"
      >  
        <div class="table-filter">
          <div>
            <el-form-item label="标题：" prop="title">
              <el-input placeholder="请输入" v-model="form.title" clearable maxlength="50" />
            </el-form-item>
          </div>
          <div v-if="sourceType === '0'">
            <el-form-item label="文件呈批单号：" prop="wjcpdh">
              <el-input placeholder="请输入" v-model="form.wjcpdh" clearable maxlength="50" />
            </el-form-item>
          </div>
          <div v-if="sourceType === '0'">
            <el-form-item label="来文单位：" prop="lwdw">
              <dg-select v-model="form.lwdw" placeholder="请选择" clearable :data="constant.BM_LWDW" filterable />
            </el-form-item>
          </div>
          <div v-if="sourceType === '0'">
            <el-form-item label="文件字号：" prop="wjzh">
              <el-input placeholder="请输入" v-model="form.wjzh" clearable maxlength="50" />
            </el-form-item>
          </div>
          <div v-if="sourceType === '0'">
            <el-form-item label="来文时间：" prop="lwsj">
              <el-date-picker
                v-model="form.lwsj"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择来文时间"
                clearable
              />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="签发人：" prop="qfrName">
              <el-input placeholder="请输入" v-model="form.qfrName" clearable maxlength="30" />
            </el-form-item>
          </div>
          <div v-if="sourceType === '0'">
            <el-form-item label="最晚反馈时间：" prop="zwfksj">
              <el-row type="flex">
                <el-date-picker
                  v-model="form.zwfksj"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm"
                  format="yyyy-MM-dd HH:mm"
                  placeholder="请选择最晚反馈时间"
                  :picker-options="pickerOptions"
                  clearable
                />
              </el-row>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="信息类别：" prop="xxlbCode">
              <!-- TODO:21号需求，暂时隐藏---快速上报中信息类别是不会被禁用的 -->
              <el-cascader :disabled=" form.isDraft == '0'"  v-model="form.xxlbCode" :options="constant.BM_XXLB" :show-all-levels="false" clearable />
            </el-form-item>
          </div>
          <div></div>
        </div>
        <div style="width: 100%">
          <el-row type="flex" justify="space-between">
            <el-col :span="22">
              <el-form-item label="正文：" prop="zw">
                <el-input
                  type="textarea"
                  :rows="5"
                  placeholder="请输入内容"
                  v-model="form.zw"
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <dg-button :disabled="!form.zw" type="primary" @click="onFeaturExtrac"> 要素提取 </dg-button>
          </el-row>
        </div>
        <div class="table-filter" style="width: 100%">
          <div style="text-ligh: right">
            <el-form-item label="涉及群体：" prop="sjqtCode">
              <dg-select
                v-model="form.sjqtCode"
                lazy-load
                :data="constant.BM_QTLB_QTXX"
                clearable
                filterable
                multiple
                placeholder="请选择"
              />
            </el-form-item>
          </div>
          <div v-show="chooseYjxs">
            <el-form-item label="指向时间：" prop="zxsj">
              <el-row type="flex">
                <el-date-picker
                  v-model="form.zxsj"
                  type="datetime"
                  :disabled="form.timeRadio"
                  value-format="yyyy-MM-dd HH:mm"
                  format="yyyy-MM-dd HH:mm"
                  placeholder="请选择指向时间"
                  clearable
                />
                <el-checkbox v-model="form.timeRadio" class="item-radio" @change="() => (form.zxsj = '')">
                  无指向时间
                </el-checkbox>
              </el-row>
            </el-form-item>
          </div>
          <div v-show="chooseYjxs">
            <el-form-item label="指向地点：" prop="zxdd">
              <el-row type="flex">
                <el-cascader v-model="form.zxdd" placeholder="请选择指向地点" :options="constant.BM_ZXDD" :show-all-levels="false" clearable />
              </el-row>
            </el-form-item>
          </div>
          <div style="width: 100%">
            <dg-upload v-model="form.fileHolderList" :server-url="'./'" size="30m" tip-msg="上传文件限制大小为 30M">
              <el-button type="primary" plain>上传文件</el-button>
              <template slot="fileList" slot-scope="{ type, name, size }">
                <i :class="`dg-icon-${type}`"></i>
                {{ `${name} (${size / 1024})KB` }}
              </template>
            </dg-upload>
          </div>
        </div>
      </el-form>
    </div>
  </collapse-card>
</template>
<script>
import { mapState } from 'vuex';
import { getFlowDetail } from '@/api/common';
import CollapseCard from '@/components/layout/CollapseCard';
import { jqxxDetail } from '@/api/police';
import { generateTimeReqestNumber } from '@/utils/common';

export default {
  name: 'BasicInfo',
  components: {
    CollapseCard
  },
  props: {
    id: {
      type: String
    },
    sourceType: {
      type: String,
      default: '1'
    },
    isEdit:{
      type: Boolean,
      default: false
    },
  },
  data() {
    // 验证最晚反馈时间不让选择此刻以前的
    var validateTime = (rule, value, callback) => {
      if (value) {
        let time = value.replace(/\-| |:/g, '').slice(0, 12);
        let currTime = generateTimeReqestNumber();
        if (time <= currTime) {
          callback(new Error('选择时间必须大于当前时间'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    // 验证指向时间必填
    var validateZxsj = (rule, value, callback) => {
      if (!value && !this.form.timeRadio) {
        callback(new Error('请选择指向时间'));
      } else {
        callback();
      }
    };

    return {
      form: {
        serialNo: '',
        title: '',
        wjcpdh: '',
        zwfksj: '',
        xxlbCode: '',
        lwdw: '',
        wjzh: '',
        lwsj: '',
        zxdd: '',
        zxsj: '',
        qfrName: '',
        sjqtCode: '',
        zw: '',
        placeRadio: false,
        timeRadio: false,
        id: '',
        fileHolderList: [],
        sendTime: '' ,// 上报时间
        isDraft:"",
      },
      chooseYjxs: false, // 信息类别是否选中了预警线索
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        xxlbCode: [{ required: true, message: '请选择信息类别', trigger: 'change' }],
        zw: [{ required: true, message: '请输入正文', trigger: 'blur' }],
        zwfksj: [{ type: 'string', validator: validateTime, trigger: 'change' }]
      },
      // 当信息类别为预警线索时，显示指向地、指向时间字段（为必填）
      yjxsRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        xxlbCode: [{ required: true, message: '请选择信息类别', trigger: 'change' }],
        zw: [{ required: true, message: '请输入正文', trigger: 'blur' }],
        zwfksj: [{ type: 'string', validator: validateTime, trigger: 'change' }],
        zxdd: [{ required: true, message: '请选择指向地点', trigger: 'change' }],
        zxsj: { required: true, validator: validateZxsj, message: '请选择指向时间', trigger: 'change' }
      },
      pickerOptions: {
        // 限制最晚反馈时间不让选择此刻以前的
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      }
    };
  },
  computed: {
    ...mapState(['constant'])
  },
  mounted() {
    this.form.id = this.id;
    if (this.id && !['3', '5'].includes(this.sourceType)) {
      getFlowDetail(this.id).then(({ data }) => {
        Object.keys(this.form).forEach((key) => {
          this.form[key] = data[key];
        });
      });
    }
    if (['3', '5'].includes(this.sourceType)) {
      // 110报警处理的id是jqxxbh
      jqxxDetail(this.sourceType == '3' ? this.$route.params.id : this.$route.params.jqxxBh).then(({ data }) => {
        this.form.zw = `报警时间：${data.bjdh}，报警内容：${data.bjnr}，案发地址：${data.afdz}，报警电话：${data.bjdh}`;
      });
    }
  },
  methods: {
    /**
     * 要素提取
     */
    onFeaturExtrac() {
      const _this = this;
      this.$dgLayer({
        title: '要素提取',
        props: {
          xsxq: this.form.zw
        },
        on: {
          success(list) {
            _this.$emit('handleCasePeople', list);
          }
        },
        component: require('@/components/FeatureExtr'),
        area: ['80%', '960px']
      });
    },
    /**
     * 提交前验证
     */
    onValidForm(isDraft) {
      let this_ = this;
      return new Promise((resolve, reject) => {
        //多选框选择后，若为数组需格式化
        if(this_.form.sjqtCode && typeof(this_.form.sjqtCode) != "string"){
          let sjqtCode = this_.form.sjqtCode.join(",");
          this_.form.sjqtCode = sjqtCode;
        }
        if (isDraft === '1') {
          resolve(this_.form);
        } else {
          this_.$refs.refForm.validate((valid) => {
            if (valid) {
              resolve(this_.form);
            } else {
              reject(false);
            }
          });
        }
      });
    }
  },
  watch: {
    // 监听信息类别是否选择“预警线索”
    'form.xxlbCode': {
      deep: true,
      handler(newVal) {
        let val = '101000,101001'; // 预警线索表码值
        let new_val = `${newVal[0]},${newVal[1]}`;
        if (new_val == val) {
          this.chooseYjxs = true;
        } else {
          this.chooseYjxs = false;
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.wrap {
  .info-title {
    margin-bottom: 20px;
  }
  .item-radio {
    height: 20px;
    margin-left: 8px;
    /deep/.el-checkbox__input {
      .el-checkbox__inner {
        border-radius: 50%;
      }
    }
  }
}
/deep/.el-date-editor.el-input {
  width: 100%;
}
</style>
